package com.ailight.smart.api.service.impl;

import cn.hutool.json.JSONUtil;
import com.ailight.smart.api.client.Esp8266NettyClient;
import com.ailight.smart.api.entity.command.LightModelCommand;
import com.ailight.smart.api.entity.dto.LightGearDTO;
import com.ailight.smart.api.enums.ModelEnums;
import com.ailight.smart.api.enums.OperationTypeEnums;
import com.ailight.smart.api.factory.ModelFactory;
import com.ailight.smart.api.service.LightOperationService;
import com.ailight.smart.api.strategy.LightOperationStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class LightOperationServiceImpl implements LightOperationService {
    // 注入工厂
    private final ModelFactory modelFactory;
    private final Esp8266NettyClient esp8266NettyClient;

    @Override
    public String operation(LightModelCommand command) {
        log.info("开始执行操作-operation:{}", JSONUtil.toJsonStr(command));
        // 先判断连接状态
        if (!esp8266NettyClient.isConnected()) {
            return "设备未连接";
        }
        if (command.getModelName().equals(ModelEnums.AUTO_MODE.getModel())
                || command.getModelName().equals(ModelEnums.MANUAL_M0DE.getModel())) {
            LightOperationStrategy strategy = modelFactory.getStrategy(ModelEnums.getModelEnum(command.getModelName()));
            // 获取到对应的策略 执行函数
            strategy.operationLight(OperationTypeEnums.getOperationTypeEnums(command.getModelName(), command.getGear()));
            return "操作成功";
        } else {
            return "当前功能不支持";
        }
    }

    @Override
    public LightGearDTO getLatestSensorData() {
        // 检查当前连接状态
        if (esp8266NettyClient.isConnected()) {
            return esp8266NettyClient.getCurrentData();
        } else {
            log.error("当前设备未连接");
            return new LightGearDTO(0, 0);
        }
    }

    @Override
    public String modifyLightState(Integer state) {
        log.info("开始执行操作-modifyLightState:{}", state);
        // 先判断连接状态
        if (!esp8266NettyClient.isConnected()) {
            log.error("设备未连接");
            return "设备未连接";
        }
        // 如果是1 那么是关灯，如果是0 那么是开灯
        if (state.equals(1)) {
            // 关灯
            // 如果是自动模式的 // 判断模式
            if (ModelEnums.AUTO_MODE.equals(esp8266NettyClient.getStateMap())) {
                // 自动模式不支持关灯 先调整为自动模式，在进行关灯
                esp8266NettyClient.sendCommand(OperationTypeEnums.ENABLE_MANUAL_MODE);
            }
            esp8266NettyClient.sendCommand(OperationTypeEnums.ENABLE_LIGHT_OFF);
            return "关灯成功";
        } else {
            // 说明是开灯 直接调节成自动模式
            esp8266NettyClient.sendCommand(OperationTypeEnums.ENABLE_AUTO_MODE);
            return "开灯成功";
        }
    }
}
